<?php

namespace app\api\controller;

use app\admin\model\coupon\Send;
use app\common\controller\Api;
use app\admin\model\user\Coupon as UserCouponModel;

/**
 * 优惠券接口
 */
class Coupon extends Api
{
    protected $noNeedLogin = ['sendCoupon'];
    protected $noNeedRight = ['*'];

    /**
     * 发券
     *
     */
    public function sendCoupon()
    {
        $id = input('id','');
        $activity = Send::get($id);
        if ( $activity->status==1){
            $this->error('已发放');
        }
        $user_coupon_model = new UserCouponModel();
        $user_id= explode(',', $activity[ 'user_id' ]);
        for ($i = 1; $i <= $activity[ 'num' ]; $i++){
            foreach ($user_id as $v) {
                $user_coupon_model->receive($id, $activity[ 'coupon_id' ], $v);
            }
        }
        //dump($activity);die;
        $activity->status=1;
        $activity->save();
        $this->success('请求成功');
    }

    //优惠券到期改状态
    public function expireCoupon()
    {
        $list = \app\admin\model\user\Coupon::where('expire_time','<',time())->select();
        foreach ($list as $k=>$v){
            $user_coupon = \app\admin\model\user\Coupon::get($v['id']);
            $user_coupon->is_used=3;
            $user_coupon->save();
        }
        $this->success('请求成功');
    }


    //我的优惠券列表
    public function myCouponList()
    {
        $param = $this->request->param();
        $param['user_id'] = $this->auth->id;
        $list = \app\admin\model\user\Coupon::tableList($param);
        foreach ($list as $item) {
            if ($item->couponinfo) {
                $shop = \app\admin\model\Shop::get($item->couponinfo->shop_id);
                $item->shop_name = $shop?$shop['shop_name']:'';
                //$item->coupon->id = is_numeric($item->coupon->id) ? IntCode::encode($item->coupon->id) : $item->coupon->id;
                $item->coupon_id = $item->couponinfo->id;
                $rd = $item->couponinfo->result_data;
                $item->result_tips = '订单满' . $rd['money'] . ($item->couponinfo->result ? '减' : '打') . $rd['number'] . ($item->couponinfo->result ? '元' : '折');
            }
            $item->expired = $item->expire_time < time();
            $item->begin = $item->begin_time < time();
        }
        $this->success('获取成功！', $list);
    }
}
